<template>
    <el-container>
        <el-header class='el-header'>
            <div style="font-size:24px;color:#333333;text-align:left;margin-left:50px;margin-top:35px;">
                实时分析医患对话
            </div>
            <div style="font-size:12px;color:#333333;text-align:left;margin-left:50px;margin-top:4px;">
                点击“开始录制”, 收集医患对话并进行实时分析
            </div>
        </el-header>

        <el-main class="main">
            <div style="margin-top:60px;margin-bottom:40px;">
                <el-image :src="docPath" style="width:15%;"></el-image>
                <div style="font-size:14px;color:#909399;margin-top:10px;">{{ text }}</div>
            </div>
            <el-button type="success" plain round style="margin-top:2px;width:200px;height:50px;font-size:16px;" @click="record()"
            :loading="loadingbut" :icon="btnIcon">{{ loadingbutText}}</el-button>
            <el-button type="info" plain round icon="el-icon-circle-check" style="margin-top:2px;width:200px;height:50px;font-size:16px;" @click="stop()">停止录音</el-button>
            <el-tooltip :content="bottomText" placement="bottom" effect="light">
                <el-button plain circle :disabled="playdisable" :icon="playicon" style="margin-top:2px;font-size:16px;" @click="resume()"></el-button>
            </el-tooltip>

            <div v-show="percenShow" style="margin-left:400px;margin-top:20px;">
                <div style="margin-top:10px;">
                    <el-progress :percentage="percentage" :text-inside="textInside" :stroke-width="strokeWidth" :show-text="showText" style="margin-top:10px;width:200px;float:left;" ></el-progress>
                    <span style="font-size:16px;color:#909399;float:left;margin-top:10px;margin-left:10px;margin-right:10px;">{{ duration }}</span>
                    <el-button plain circle icon="el-icon-video-play" style="font-size:16px;float:left;" @click="playaudio();percentageChange()"></el-button>
                    <el-tooltip content="下载WAV音频" placement="bottom" effect="light">
                        <el-button plain circle icon="el-icon-download" style="font-size:16px;float:left;" @click="downloadwav()"></el-button>
                    </el-tooltip>
                    <el-tooltip content="点击上传文件开始分析" placement="bottom" effect="light">
                        <el-button plain circle icon="el-icon-upload2" style="font-size:16px;float:left;" @click="dialogVisible=true"></el-button>
                    </el-tooltip>
                </div>
            </div>

            <el-dialog
            title="患者信息"
            :visible.sync="dialogVisible"
            width="30%"
            center>
            <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="姓名">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="form.gender">
                    <el-radio label="男"></el-radio>
                    <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期">
                    <el-date-picker type="date" format="yyyy.M.d" value-format="yyyy.M.d" placeholder="选择日期" v-model="form.birth" style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="问诊日期">
                    <el-date-picker type="date" defalut-value="form.speech" format="yyyy.M.d" value-format="yyyy.M.d" placeholder="选择日期" v-model="form.speech" style="width: 100%;"></el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false;upload()">确 定</el-button>
            </span>
            </el-dialog>

        </el-main>
    </el-container>
</template>

<script>
import axios from 'axios'
import icon_url from '@/assets/icon-2.png'
import doc_url from '@/assets/bgd.png'
import Recorder from 'js-audio-recorder'
import Player from 'js-audio-recorder'
import {Stretch} from 'vue-loading-spinner'
export default {
    name:"upload",
    components: {
      Stretch,
    },
    data() {
        return {
            name: "上传文件",
            checkStatus: "",
            activeTab: 'first',
            iconPath:icon_url,
            docPath: doc_url,
            dialogVisible: false,
            form:{
                name: '',
                gender: '',
                birth: '',
                speech: '',
            },
            recorder: undefined,
            strokeWidth: 20,
            textInside: true,
            showText: false,
            text: "点击按钮 开始录制医患对话",
            loadingbut:false,
            loadingbutText:"开始录制",
            btnIcon:"el-icon-microphone",
            playicon: "el-icon-video-pause",
            bottomText: "点击暂停录音",
            playdisable: true,
            audio: null,
            wavaudio: null,
            mp3audio: null,
            percentage: 0,
            percenShow: false,
            duration: "",
            duration_int: 0,
            timer: null,
        }
    },
    created(){
        this.form.speech = this.getDate();
        console.log(this.form);
    },
    beforeDestroy(){
        if(this.timer){
            clearInterval(this.timer); 
        }
    },
    methods: {
        goTo1(){
            this.$router.push({ path:'/dialogue-select' })
        },
        goTo2(){
            this.$router.push({ path:'/recordDialogue' })
        },
        record(){
            Recorder.getPermission().then(() => {
                console.log('给权限了');
            }, (error) => {
                console.log(`${error.name} : ${error.message}`);
            });
            this.recorder = new Recorder({sampleBits: 16, sampleRate: 16000, numChannels: 1});
            this.recorder.start().then(() => {
                console.log("Recording...")
                this.playdisable = false;
                this.text = "录制中...";
                this.loadingbut = true;
                this.loadingbutText = "正在录制";
                this.btnIcon = "el-icon-loading";
            }, (error) => {
                // 出错了
                console.log(`${error.name} : ${error.message}`);
            });
        },
        stop(){
            this.recorder.stop();
            this.text = "录制完成!";
            this.loadingbut = false;
            this.playdisable = true;
            this.loadingbutText = "重新录制";
            this.btnIcon = "el-icon-microphone";
            this.playicon = "el-icon-video-pause";
            this.bottomText = "点击暂停录音";
            var b  =  (Math.round(this.recorder.duration*100))/100;
            this.duration_int = Math.round(this.recorder.duration)
            this.duration = b + 's';
            this.percentage = 0;
            this.percenShow = true;
            this.audio = this.recorder.getChannelData();
            this.wavaudio = this.recorder.getWAVBlob();
        },
        resume(){
            if(this.playicon == "el-icon-video-pause"){
                console.log("Pause");
                this.recorder.pause();
                this.text = "录音已暂停";
                this.loadingbutText = "暂停中";
                this.playicon = "el-icon-video-play";
                this.bottomText = "点击继续录音";
            }else{
                console.log("Resume");
                this.recorder.resume();
                this.text = "录制中...";
                this.loadingbutText = "正在录制";
                this.playicon = "el-icon-video-pause";
                this.bottomText = "点击暂停录音";
            };
        },
        async playaudio(){
            var AudioContext = window.AudioContext || window.webkitAudioContext
            var ctx = new AudioContext()
            const audioData = await this.wavaudio.arrayBuffer()
            ctx.decodeAudioData(
                    audioData,
                    function (buffer) {
                            var sourceNode = ctx.createBufferSource()
                            sourceNode.buffer = buffer
                            sourceNode.connect(ctx.destination)
                            sourceNode.start(0)
                    },
                    function () {
                            // 错误处理
                    }
            )
        },
        percentageChange(){
            var delta = (Math.round(10/this.duration_int*10))/10;
            this.percentage = 0;
            this.timer = setInterval(()=>{
                if(this.percentage == 100){
                    clearInterval(this.timer);
                }
                this.percentage += delta; 
                if(this.percentage >= 100){
                    this.percentage = 100
                }
            },100);
        },
        downloadwav(){
            this.recorder.downloadWAV("recorder");
        },
        convertToMp3() {
            // 获取wav头信息
            var lamejs = require("lamejs");
            // const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
            // const { channels, sampleRate } = wav;
            var channels = 1;
            var sampleRate = 16000;
            const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
            // 获取左右通道数据
            const result = this.recorder.getChannelData()
            const buffer = [];

            const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
            const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
            const remaining = leftData.length + (rightData ? rightData.length : 0);

            const maxSamples = 1152;
            for (let i = 0; i < remaining; i += maxSamples) {
                const left = leftData.subarray(i, i + maxSamples);
                let right = null;
                let mp3buf = null;

                if (channels === 2) {
                    right = rightData.subarray(i, i + maxSamples);
                    mp3buf = mp3enc.encodeBuffer(left, right);
                } else {
                    mp3buf = mp3enc.encodeBuffer(left);
                }

                if (mp3buf.length > 0) {
                    buffer.push(mp3buf);
                }
            }

            const enc = mp3enc.flush();

            if (enc.length > 0) {
                buffer.push(enc);
            }

            return new Blob(buffer, { type: 'audio/mp3' });
        },
        getDate(){
            var now = new Date();
            var year = now.getFullYear();    
            var month = now.getMonth() + 1;  
            var day = now.getDate();  
            var date = year.toString() + "." + month.toString() + "." + day.toString();   
            return date
        },
        upload(){
            this.mp3audio = this.convertToMp3();
            console.log(this.mp3audio);
            let formData = new FormData();
            formData.append('file', this.mp3audio);
            var genders = {"男":"male", "女":"female"};
            var gender = genders[this.form.gender];
            var audioname = this.form.name + '_' + gender + '_' + this.form.birth + this.form.speech + '.mp3';
            formData.append('name', audioname);
            axios.post("http://localhost:8000/dialogue/upload_record/", formData,{
                headers: {
                    'Content-Type': 'multipart/form-data'
            },
            }).then(res => {
                console.log(res);
                this.$router.push({
                    name:'Record_Load',
                })
            });
        }




    },
}
</script>
<style scoped>
    .el-aside{
        background-color: #2b3a49;
    }
    
    .main{
        background-color: #f3f3f4;
        margin-top:80px;
    }
    .main-container{
        position:absolute;
        height:100%;
        width:100%;
    }
    .card-box{
        margin-top:100px;
    }
    .tab-title{
        color:#fff;
    }
    .box-card{
        width:300px;
        height:320px;
        margin:auto;
    }

</style>